package com.zheng.client;


import com.zheng.RpcEncoder;
import com.zheng.handler.UserClientHandler;
import com.zheng.request.RpcRequest;
import com.zheng.serializer.JSONSerializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.apache.curator.framework.CuratorFramework;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  @author: zheng
 *  @Date: 2020-06-28 23:04
 *  @Description:消费者
 */
public class RPCConsumer {


    private  String ip;

    private  Integer port;

    private Long time;

    private String path;//zk 路径


    public RPCConsumer(String ip, Integer port,Long time,String path){
        this.ip=ip;
        this.port=port;
        this.time=time;
        this.path=path;

    }

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    //1.创建一个线程池对象,处理自定义事件
    private  ExecutorService executorService= Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private  UserClientHandler userClientHandler;

    //创建代理对象
    public Object createProxy(Class<?> serverClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serverClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //初始化客户端Client
                if(userClientHandler==null){
                    initClient();
                }
                //设置参数
                RpcRequest rpcRequest=new RpcRequest();
                rpcRequest.setClassName(method.getDeclaringClass().getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setParameters(args);

                List<Class<?>> list=new ArrayList<>();
                for(Object o:args){
                    Class<?> aClass=o.getClass();
                    list.add(aClass);
                }
                rpcRequest.setParameterTypes((Class<?>[])list.toArray(new Class<?>[args.length]));
                userClientHandler.setParam(rpcRequest);
                //请求数据
                return executorService.submit(userClientHandler).get();
            }


        });


    }

    //初始化客户端
    public   void initClient() throws InterruptedException {
        userClientHandler=new UserClientHandler(path,ip,port);

        //创建连接池对象
        NioEventLoopGroup group=new NioEventLoopGroup();
        //创建客户端的引导对象
        Bootstrap bootstrap=new Bootstrap();
        //配置启动引导对象
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                //设置请求协议
                .option(ChannelOption.TCP_NODELAY,true)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                //监听channel
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取ChannelPipline
                        ChannelPipeline pipeline=socketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(userClientHandler);
                    }
                });
        bootstrap.connect(ip,port).sync();
    }

}
